<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of router
 *
 * @author dmitry
 * 
 * 
 */

class Access_Router {
    //put your code here
    private $registry ;

    private $path ;

    private $args = array() ;
    
    private $id ;


    function __construct($registry) 
    {

            $this->registry = $registry ;
            

    }
    
    function setPath($path) 
    {

        $path = trim($path, '/\\') ;

        $path .= DIR;


        if (!is_dir($path)) {

                throw new Exception ('Invalid controller path: `' . $path . '`');

        }


        $this->path = $path;

    }
    
    private function getController(&$file, &$controller, &$action, &$args) 
    {

        $route = (empty($_GET['route'])) ? '' : $_GET['route'];


        if (empty($route)) { $route = 'index'; }


        // get parts

        $route = trim($route, '/\\');

        $parts = explode('/', $route);
        
        $countParts = count($parts) ;
        
        
        if ($countParts > 2) {
            
            $this->id = $parts[2] ;
            for ($i=2; $i<=$countParts; $i++){
                unset ($parts[$i]) ;
            }
            
        }

        // find controller

        $cmdPath = $this->path;

        foreach ($parts as $part) {

                $fullPath = $cmdPath . $part;


                // find dir

                if (is_dir($fullPath)) {

                        $cmdPath .= $part . DIR;

                        array_shift($parts);

                        continue;

                }


                // find file

                if (is_file($fullPath . '.php')) {

                        $controller = $part;

                        array_shift($parts);

                        break;

                }

        }


        if (empty($controller)) { $controller = 'index'; };


        // get action

        $action = array_shift($parts);

        if (empty($action)) { $action = 'index'; }


       // $file = $cmd_path . $controller . '.php';
        $file = 'app/controller/' . $controller . '.php' ;

        $args = $parts;

    }
    
    function delegate() {

        // path

        $this->getController($file, $controller, $action, $args);


        // file accesseble?

        if (!is_readable($file)) {
            

                die ('404 Not Found');

        }


        // include file

        require_once $file;


        // make controller

        $class = 'controller_'.$controller;

        $controller = new $class($this->registry);


        // action is accessible

        if (!is_callable(array($controller, $action))) {

                die ('<h3>' . $action . ' 404 Not Found </h3>');

        }


        // make action

        $controller->$action($this->id);

    }

    
}

?>
